<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\TakeDelivery;
use Symfony\Component\Translation\Dumper\IniFileDumper;

class TakeDeliveryController extends BaseController
{
	/**
	 * 提货人列表
	 * @return void
	 */
	public function list()
	{
		$rows = TakeDelivery::where(['user_id' => $this->user_id])->paginate()->items();
		$this->writeJson($rows);
	}
	
	/**
	 * 添加提货人
	 * @return void
	 */
	public function addTakeDelivery()
	{
		$name = $this->request->post('name');
		$mobile = $this->request->post('mobile');
		$default = $this->request->post('default/d', 2);
		$data = [
			'user_id'=>$this->user_id,
			'name'=>$name,
			'mobile'=>$mobile,
			'default'=>$default
		];
		if ($default == 2) {
			$row = TakeDelivery::where(['user_id' => $this->user_id, 'default' => 1])->find();
			if (!$row) {
				$data['default'] = 1;
			}
		} else {
			TakeDelivery::where(['user_id' => $this->user_id, 'default' => 1])->update(['default' => 2]);
		}
		TakeDelivery::create($data);
		$this->writeJson();
	}
	
	/**
	 * 设置默认提货人
	 */
	function setDefaultTakeDelivery()
	{
		$take_delivery_id = $this->request->post('take_delivery_id/d');
		TakeDelivery::where(['user_id' => $this->user_id])->update(['default' => 2]);
		TakeDelivery::where(['id' => $take_delivery_id])->update(['default' => 1]);
		$this->writeJson();
	}
	
	/**
	 * 删除提货人
	 * @return void
	 */
	function deleteTakeDelivery()
	{
		$take_delivery_id = $this->request->post('take_delivery_id/d');
		$row = TakeDelivery::where(['user_id' => $this->user_id])->findOrFail($take_delivery_id);
		$row->delete();
		$this->writeJson();
	}
	
	
	/**
	 * 编辑提货人
	 */
	public function editTakeDelivery()
	{
		
		$take_delivery_id = $this->request->post('take_delivery_id/d');
		$name = $this->request->post('name');
		$mobile = $this->request->post('mobile');
		$default = $this->request->post('default/d',2);
		$row = TakeDelivery::findOrFail($take_delivery_id);
		
		if (!empty($name)){
			$row->name = $name;
		}
		if (!empty($mobile)){
			$row->mobile = $mobile;
		}
		if (!empty($default)){
			$row->default = $default;
		}
		$row->save();
		if ($default == 1) {
			TakeDelivery::where(['user_id' => $this->user_id,['id','<>',$row->id]])->update(['default' => 2]);
		}
		$this->writeJson();
	}
	
	/**
	 * 获取默认提货人
	 * @return void
	 */
	function getDefaultTakeDelivery()
	{
		$row = TakeDelivery::where(['user_id' => $this->user_id, 'default' => 1])->find();
		$this->writeJson($row);
	}
	
	/**
	 * 获取指定提货人
	 * @return void
	 */
	function getTakeDelivery()
	{
		$take_delivery_id = $this->request->get('take_delivery_id/d');
		$row = TakeDelivery::findOrFail($take_delivery_id);
		$this->writeJson($row);
	}
}
